#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <iostream>
#include <QMessageBox>
#include "ms_window.h"
#include "ms_window2.h"
#include <QDragEnterEvent>
#include <QMimeData>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::WindowCloseButtonHint|Qt::WindowMinimizeButtonHint);
    this->setFixedSize(this->width(),this->height());
    ui->label_show->installEventFilter(this);
    ui->label_show->setAcceptDrops(true);
}

MainWindow::~MainWindow()
{
    delete ui;
}

QImage MainWindow::AdjustImageSize(QImage qimage,QLabel *qLabel)
{
    QImage image;
    QSize imageSize = qimage.size();
    QSize labelSize = qLabel->size();

    double widthRatio = 1.0*imageSize.width() / labelSize.width();
    double heightRatio = 1.0*imageSize.height() / labelSize.height();
    if (widthRatio>heightRatio)
        image = qimage.scaledToWidth(labelSize.width());
    else
        image = qimage.scaledToHeight(labelSize.height());
    return image;
}

void MainWindow::ShowImage(Image& img)
{
    //if(img.GetHeight()>ui->label_show->height() || img.GetWidth()>ui->label_show->width())
      //  img.Resize(600,600);

    QImage image(img.GetData(),img.GetWidth(),img.GetHeight(),QImage::Format_BGR888);
    // image = AdjustImageSize(image,ui->label_show);
    ui->label_show->setPixmap(QPixmap::fromImage(image));
    ui->label_show->setAlignment((Qt::AlignCenter));
}

void MainWindow::Reset()
{
    ui->horizontalSlider_duibi->setValue(0);
    ui->horizontalSlider_brightness->setValue(0);
    ui->horizontalSlider_erzhi->setValue(128);
    ui->horizontalSlider_baohe->setValue(0);

    ui->horizontalSlider_2->setValue(0);

    ui->label_light->setText(QString::number(0));
    ui->label_2->clear();

    ui->horizontalSlider_B->setValue(0);
    ui->horizontalSlider_G->setValue(0);
    ui->horizontalSlider_R->setValue(0);
}

void MainWindow::on_action_Open_triggered()
{
    QString curDir = QDir::currentPath();
    QString fileName = QFileDialog::getOpenFileName(this, "选择图片", curDir, "Images (*.bmp)");
    if (fileName.isEmpty())
        return;

    filePath = fileName;
    srcImage.ReadBMP(filePath.toStdString().c_str());
    srcImage.Flip(1);
    curImage.ReadBMP(filePath.toStdString().c_str());
    curImage.Flip(1);

    Reset();

    std::cout << filePath.toStdString() << std::endl;

    ShowImage(curImage);
}

void MainWindow::SaveImage()
{
    if(CheckImageFail())
        return;

    QString curDir = QDir::currentPath();
    QString fileName = QFileDialog::getSaveFileName(this, "保存图片", curDir, "Images (*.bmp)");
    if (fileName.isEmpty())
        return;

    QString savePath = fileName;
    curImage.Flip(1);
    curImage.WriteBMP(savePath.toStdString().c_str());
}

void MainWindow::on_pushButton_save_clicked()
{
    SaveImage();
}


void MainWindow::on_action_Save_triggered()
{
    SaveImage();
}

bool MainWindow::CheckImageFail()
{
    if(curImage.GetData()==NULL)
    {
        QMessageBox::warning(nullptr, "提示", "请先选择一张图片！", QMessageBox::Yes |  QMessageBox::Yes);
        return true;
    }
    return false;
}

void MainWindow::on_pushButton_gray_clicked()
{
    if(CheckImageFail())
        return;

    curImage.Grayed();

    ShowImage(curImage);
}

void MainWindow::on_pushButton_origin_pressed()
{
    ShowImage(srcImage);
}

void MainWindow::on_pushButton_origin_released()
{
    ShowImage(curImage);
}

void MainWindow::on_pushButton_turnleft_clicked()
{
    if(CheckImageFail())
        return;

    curImage.Rotate(-90);

    ShowImage(curImage);
}


void MainWindow::on_pushButton_flip_clicked()
{
    if(CheckImageFail())
        return;

    curImage.Flip(0);

    ShowImage(curImage);
}


void MainWindow::on_pushButton_recover_clicked()
{
    srcImage.ReadBMP(filePath.toStdString().c_str());
    srcImage.Flip(1);
    curImage.ReadBMP(filePath.toStdString().c_str());
    curImage.Flip(1);

    Reset();

    std::cout << filePath.toStdString() << std::endl;

    ShowImage(curImage);
}


void MainWindow::on_pushButton_junzhi_clicked()
{
    if(CheckImageFail())
        return;

    curImage = curImage.MeanFilter(9);

    ShowImage(curImage);
}


void MainWindow::on_pushButton_gradient_clicked()
{
    if(CheckImageFail())
        return;

    curImage = curImage.gradient();

    ShowImage(curImage);
}


void MainWindow::on_pushButton_yuanxing_clicked()
{
    if(CheckImageFail())
        return;

    curImage.count_circle();
    Image img = curImage;

    ShowImage(img);

    QString text("圆的数量：");
    text += QString::number(curImage.circleNum);
    ui->label_2->setText(text);
}


void MainWindow::on_horizontalSlider_erzhi_valueChanged(int value)
{
    if(curImage.GetData()==NULL)
    {
        ui->horizontalSlider_erzhi->setValue(128);
        return;
    }

    QString sValue = QString::number(value);
    ui->label_yuzhi->setText(QString(sValue));
    Image img = curImage;
    img.gray2bw(value);

    ShowImage(img);
}


void MainWindow::on_horizontalSlider_erzhi_sliderReleased()
{
    if(curImage.GetData()==NULL)
    {
        return;
    }

    int value = ui->horizontalSlider_erzhi->value();
    curImage.gray2bw(value);
}


void MainWindow::on_horizontalSlider_duibi_valueChanged(int value)
{
    if(curImage.GetData()==NULL)
    {
        ui->horizontalSlider_duibi->setValue(0);
        return;
    }

    double mean = curImage.Mean();

    Image img = curImage;
    img = img.Contrast(value, mean);

    ShowImage(img);
}


void MainWindow::on_horizontalSlider_duibi_sliderReleased()
{
    if(curImage.GetData()==NULL)
    {
        return;
    }

    double mean = curImage.Mean();
    int value = ui->horizontalSlider_duibi->value();
    curImage = curImage.Contrast(value,mean);
}


void MainWindow::on_horizontalSlider_2_valueChanged(int value)
{
    if(curImage.GetData()==NULL)
    {
        ui->horizontalSlider_2->setValue(0);
        return;
    }

    Image img = curImage;

    int width = img.GetWidth();
    int height = img.GetHeight();

    int newWidth = width + value * 100;
    int newHeight = height + value * 100;


    if(newWidth < 100 || newHeight < 100)
    {
        ui->horizontalSlider_2->setValue(lastSlideVal);
        return;
    }

    img.Resize(newHeight,newWidth);

    ShowImage(img);
    lastSlideVal = value;
}


void MainWindow::on_horizontalSlider_2_sliderReleased()
{
    if(curImage.GetData()==NULL)
    {
        return;
    }

    int value = ui->horizontalSlider_2->value();

    int width = curImage.GetWidth();
    int height = curImage.GetHeight();

    int newWidth = width + value * 100;
    int newHeight = height + value * 100;

    curImage.Resize(newHeight, newWidth);
}

void MainWindow::on_horizontalSlider_R_valueChanged(int value)
{
    if(curImage.GetData()==NULL)
    {
        ui->horizontalSlider_R->setValue(0);
        return;
    }

    Image img = curImage;
    img.addRGB(value, 2);

    ShowImage(img);
}

void MainWindow::on_horizontalSlider_R_sliderReleased()
{
    if(curImage.GetData()==NULL)
    {
        return;
    }

    int value = ui->horizontalSlider_R->value();
    curImage.addRGB(value,2);
}
void MainWindow::on_horizontalSlider_G_valueChanged(int value)
{
    if(curImage.GetData()==NULL)
    {
        ui->horizontalSlider_G->setValue(0);
        return;
    }

    Image img = curImage;
    img.addRGB(value, 1);

    ShowImage(img);
}

void MainWindow::on_horizontalSlider_G_sliderReleased()
{
    if(curImage.GetData()==NULL)
    {
        return;
    }

    int value = ui->horizontalSlider_G->value();
    curImage.addRGB(value,1);
}
void MainWindow::on_horizontalSlider_B_valueChanged(int value)
{
    if(curImage.GetData()==NULL)
    {
        ui->horizontalSlider_B->setValue(0);
        return;
    }

    Image img = curImage;
    img.addRGB(value, 0);

    ShowImage(img);
}

void MainWindow::on_horizontalSlider_B_sliderReleased()
{
    if(curImage.GetData()==NULL)
    {
        return;
    }

    int value = ui->horizontalSlider_B->value();
    curImage.addRGB(value,0);
}

void MainWindow::on_horizontalSlider_brightness_valueChanged(int value)
{
    if(curImage.GetData()==NULL)
    {
        ui->horizontalSlider_brightness->setValue(0);
        return;
    }

    Image img = curImage;
    img.ChangeBrightness(value);
    ShowImage(img);
    ui->label_light->setText(QString::number(value));
}

void MainWindow::on_action_meanFliter_triggered()
{
    if(CheckImageFail())
        return;

    curImage = curImage.MeanFilter(9);

    ShowImage(curImage);
}


void MainWindow::on_action_gradient_triggered()
{
    if(CheckImageFail())
        return;

    curImage = curImage.gradient();

    ShowImage(curImage);
}
void MainWindow::on_action_yuanxing_clicked_triggered()
{
    if(CheckImageFail())
        return;

    curImage.count_circle();
    Image img = curImage;

    ShowImage(img);

    QString text("圆的数量：");
    text += QString::number(curImage.circleNum);
    ui->label_2->setText(text);
}
void MainWindow::on_pushButton_rice_clicked()
{
    if(CheckImageFail())
        return;

    curImage.Rice();

    ShowImage(curImage);

    QString text("大米数量：");
    text += QString::number(curImage.riceNum);
    ui->label_2->setText(text);
}

void MainWindow::on_horizontalSlider_baohe_valueChanged(int value)
{
    if(curImage.GetData()==NULL)
    {
        ui->horizontalSlider_baohe->setValue(0);
        return;
    }

    Image img = curImage;
    img.Saturation(value);

    ShowImage(img);
}


void MainWindow::on_horizontalSlider_brightness_sliderReleased()
{
    if(curImage.GetData()==NULL)
    {
        ui->horizontalSlider_brightness->setValue(0);
        return;
    }

    int value = ui->horizontalSlider_brightness->value();
    curImage.ChangeBrightness(value);
    ShowImage(curImage);
}


void MainWindow::on_horizontalSlider_baohe_sliderReleased()
{
    if(curImage.GetData()==NULL)
    {
        ui->horizontalSlider_baohe->setValue(0);
        return;
    }

    int value = ui->horizontalSlider_baohe->value();
    curImage.Saturation(value);

    ShowImage(curImage);
}


void MainWindow::on_action_clear_triggered()
{
    Reset();
    curImage.Reset();
    srcImage.Reset();
    ui->label_show->clear();
}


void MainWindow::on_action_3_triggered()
{
    if(CheckImageFail())
        return;

    curImage.Rice();

    ShowImage(curImage);

    QString text("大米的数量：");
    text += QString::number(curImage.riceNum);
    ui->label_2->setText(text);
}


void MainWindow::on_action_4_triggered()
{
    Mosaic();
}


void MainWindow::on_pushButton_masaike_clicked()
{
    Mosaic();
}

void MainWindow::Mosaic()
{
    if(CheckImageFail())
        return;

    msWindow = new ms_window;
    msWindow->show();
    connect(msWindow,SIGNAL(SendSignal(int,int,int,int)),this,SLOT(SetMosaic(int,int,int,int)));
}

void MainWindow::SetMosaic(int x1,int y1,int x2,int y2)
{
    if(curImage.GetData()==NULL)
        return;

    curImage = curImage.Mosaic(x1,y1,x2,y2);

    ShowImage(curImage);
}

void MainWindow::on_pushButton_min_clicked()
{
    if(curImage.GetData()==NULL)
        return;

    curImage = -curImage;

    ShowImage(curImage);
}


void MainWindow::on_action_min_triggered()
{
    if(curImage.GetData()==NULL)
        return;

    curImage = -curImage;

    ShowImage(curImage);
}

int i=0;
bool MainWindow::eventFilter(QObject  *obj, QEvent *event)
{
    if (obj == ui->label_show)//当事件发生在u1（为Qlabel型）控件上
    {
        if (event->type() == QEvent::DragEnter)
        {
            // [[2]]: 当拖放时鼠标进入label时, label接受拖放的动作
            QDragEnterEvent *dee = dynamic_cast<QDragEnterEvent *>(event);
            dee->acceptProposedAction();
            return true;
        }
        else if (event->type() == QEvent::Drop)
        {
                        // [[3]]: 当放操作发生后, 取得拖放的数据
            QDropEvent *de = dynamic_cast<QDropEvent *>(event);
            QList<QUrl> urls = de->mimeData()->urls();
            if (urls.isEmpty()) { return true; }
            filePath = urls.first().toLocalFile();
            srcImage.ReadBMP(filePath.toStdString().c_str());
            srcImage.Flip(1);
            curImage.ReadBMP(filePath.toStdString().c_str());
            curImage.Flip(1);

            Reset();

            std::cout << filePath.toStdString() << std::endl;

            ShowImage(curImage);
        }

        if (event->type() == QEvent::MouseButtonPress)//当为双击事件时
        {
            i++;
            if (i % 2 == 0) //此处为双击一次全屏，再双击一次退出
            {
                ui->label_show->setWindowFlags(Qt::Dialog);
                ui->label_show->showFullScreen();//全屏显示
            }
            else
            {
                ui->label_show->setWindowFlags(Qt::SubWindow);
                ui->label_show->showNormal();//退出全屏
                ui->label_show->resize(751,571);
                ui->label_show->setAlignment(Qt::AlignCenter);
            };
        }

        return QObject::eventFilter(obj, event);
    }

}
void MainWindow::on_action_UpCat_triggered()
{
    if(CheckImageFail())
        return;
    QString curDir = QDir::currentPath();
    QString fileName = QFileDialog::getOpenFileName(this, "选择图片", curDir, "Images (*.bmp)");
    if (fileName.isEmpty())
        return;

    filePath = fileName;
    srcImage.ReadBMP(filePath.toStdString().c_str());
    srcImage.Flip(1);
    curImage=curImage.Cat(srcImage,1);
    ShowImage(curImage);
}
void MainWindow::on_action_DownCat_triggered()
{
    if(CheckImageFail())
        return;
    QString curDir = QDir::currentPath();
    QString fileName = QFileDialog::getOpenFileName(this, "选择图片", curDir, "Images (*.bmp)");
    if (fileName.isEmpty())
        return;

    filePath = fileName;
    srcImage.ReadBMP(filePath.toStdString().c_str());
    srcImage.Flip(1);
    curImage=curImage.Cat(srcImage,2);
    ShowImage(curImage);
}
void MainWindow::on_action_LeftCat_triggered()
{
    if(CheckImageFail())
        return;
    QString curDir = QDir::currentPath();
    QString fileName = QFileDialog::getOpenFileName(this, "选择图片", curDir, "Images (*.bmp)");
    if (fileName.isEmpty())
        return;

    filePath = fileName;
    srcImage.ReadBMP(filePath.toStdString().c_str());
    srcImage.Flip(1);
    curImage=curImage.Cat(srcImage,3);
    ShowImage(curImage);
}
void MainWindow::on_action_RightCat_triggered()
{
    if(CheckImageFail())
        return;
    QString curDir = QDir::currentPath();
    QString fileName = QFileDialog::getOpenFileName(this, "选择图片", curDir, "Images (*.bmp)");
    if (fileName.isEmpty())
        return;

    filePath = fileName;
    srcImage.ReadBMP(filePath.toStdString().c_str());
    srcImage.Flip(1);
    curImage=curImage.Cat(srcImage,4);
    ShowImage(curImage);
}
void MainWindow::on_action_Cut_triggered()
{
    if(CheckImageFail())
        return;

    msWindow2 = new ms_window2;
    msWindow2->show();
    connect(msWindow2,SIGNAL(SendSignal(int,int,int,int)),this,SLOT(SetCut(int,int,int,int)));
}

void MainWindow::SetCut(int x1,int y1,int x2,int y2)
{
    if(curImage.GetData()==NULL)
        return;

    curImage = curImage.Cut(x1,y1,x2,y2);

    ShowImage(curImage);
}
